package com.study.lxy.threadpool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class MyThreadPool<Job extends Runnable> implements ThreadPool<Job> {

    private final LinkedList<Job> jobs = new LinkedList<>();
    private final List<Worker> workers = Collections.synchronizedList(new ArrayList<>());

    private static final int MAX_WORKER_NUMS = 10;

    private static final int DEFAULT_WORKER_NUMS = 5;

    private static final int MIN_WORKER_NUMS = 1;

    private int workerNums = DEFAULT_WORKER_NUMS;

    /**
     *
     */
    public MyThreadPool(){
        initWorkers(DEFAULT_WORKER_NUMS);
    }

    private void initWorkers(int num){
        for(int i = 0; i < num ; i++){
            Worker worker = new Worker();
            workers.add(worker);
            Thread t = new Thread(worker);
            t.start();
        }
    }


    @Override
    public void execute(Job job) {
        synchronized (jobs){
            jobs.addLast(job);
            jobs.notify();
        }
    }

    @Override
    public void shutdown() {
        for(Worker worker : workers){
            worker.shutdown();
        }
    }

    @Override
    public void addWorkers(int num) {
        synchronized (jobs){
            int addNum = workerNums + num > MAX_WORKER_NUMS ? MAX_WORKER_NUMS - workerNums : num;
            initWorkers(num);
            this.workerNums += addNum;
        }
    }

    @Override
    public void removeWorkers(int num) {
        synchronized (jobs){
            int removeNum = workerNums - num > MIN_WORKER_NUMS ? num : workerNums - MIN_WORKER_NUMS;

            while (removeNum > 0){
                Worker worker = workers.get(0);
                if(workers.remove(worker)){
                    worker.shutdown();
                    removeNum--;
                }
            }
            this.workerNums -= removeNum;
        }
    }

    @Override
    public int getJobSize() {
        return jobs.size();
    }


    class Worker implements Runnable{
        private volatile boolean running = true;
        @Override
        public void run() {
            while (running) {
                Job job = null;
                synchronized (jobs) {
                    while (jobs.isEmpty()){
                        try {
                            jobs.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            e.printStackTrace();
                        }
                    }
                    job = jobs.removeFirst();
                }
                if(job != null){
                    job.run();
                }
            }
        }

        public void shutdown(){
            running = false;
        }
    }

}
